package com.wolf.coder;

import com.wolf.core.Header;
import com.wolf.core.Protocol;
import com.wolf.core.ResponseEntity;
import com.wolf.serialization.SerialFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @auth: dylan
 * @Desc:编码器
 * @Time: 2024/4/30
 */
public class WolfEncoder extends MessageToByteEncoder<Protocol<ResponseEntity>> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Protocol<ResponseEntity> protocol, ByteBuf byteBuf) throws Exception {
        Header header=protocol.getHeader();
        byteBuf.writeShort(header.getMagic());
        byteBuf.writeShort(header.getCommand());
        byteBuf.writeByte(header.getSerialType());
        byte[] bytes = SerialFactory.get(header.getSerialType()).serializer(protocol.getContent());
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
    }
}
